package com.chenglin.picturepicker.adapter

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.chenglin.picturepicker.bean.MediaBean
import com.chenglin.picturepicker.bean.PhotoFileBean
import com.chenglin.picturepicker.bean.ScanImageBean
import com.chenglin.picturepicker.util.UriUtil
import com.chenglin.picturepicker.databinding.ActivitySelectPhotoBinding
import com.google.android.material.snackbar.Snackbar
import java.io.File
import java.io.Serializable
import kotlin.collections.ArrayList
import kotlin.collections.HashMap


class SelectPhotoActivity : AppCompatActivity() {

    private lateinit var binding: ActivitySelectPhotoBinding
    private var topPhotoList = arrayListOf<MediaBean>()    //顶部4张图片
    private var totalPhotoList = arrayListOf<MediaBean>()  //所有图片
    private var bottomPhotoList = arrayListOf<MediaBean>()  //底部图片
    private var userSelectList = arrayListOf<MediaBean>()   //用户选择的图片类型
    private lateinit var mCurrentPhotoPath:String  //存储图片位置
    //图片路径 + 图片集合
    var list = arrayListOf<PhotoFileBean>()
    val allPhotosTemp: HashMap<String, ArrayList<MediaBean>> = HashMap() //所有照片


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
         binding = ActivitySelectPhotoBinding.inflate(layoutInflater)
        setContentView(binding.root)
         initView()
        queryAllPhotoInfo()
        binding.tvOk.setOnClickListener {
            var intent = Intent()
            intent.putExtra("selectList",userSelectList as Serializable)
            setResult(RESULT_OK,intent)
            finish()
        }

        binding.conSelectFile.setOnClickListener {
            list.clear()

            list.add(PhotoFileBean("全部图片","全部图片",totalPhotoList.size,totalPhotoList[0].path))
            for (entry in allPhotosTemp.entries){
                val split = entry.key.split("/")
                list.add(PhotoFileBean(entry.key,"${split[split.size-1]}",entry.value.size,entry.value[0].path))
            }
            binding.rvFile.adapter?.notifyDataSetChanged()
            binding.conFile.visibility = View.VISIBLE
        }

        binding.rvFile.layoutManager = LinearLayoutManager(this)
        binding.rvFile.adapter = TitleAdapter(this,list,object :TitleAdapter.TitleItemClick{
            override fun onItemClickListener(fileName: String,photoFileBean: PhotoFileBean) {
                binding.conFile.visibility = View.GONE
                binding.tvCameraFile.text = fileName
                var currentList : ArrayList<MediaBean> = if ( photoFileBean.fileName != "全部图片"){
                    allPhotosTemp[photoFileBean.hashMapKey]!!
                }else{
                    totalPhotoList
                }
                disconnectList(currentList)
                binding.rvPhoto.adapter?.notifyDataSetChanged()

            }

        })
        binding.conFile.setOnClickListener {
            binding.conFile.visibility =View.GONE
        }
    }

    /**
     * 初始化 recyclerView
     */
    private fun initView(){


        val registerCamera = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            //拍照结果返回
          if (it.resultCode == RESULT_OK){
              val realPath = mCurrentPhotoPath
              userSelectList.clear()
              Log.e("realPath",realPath)
              userSelectList.add(MediaBean(realPath,0,"",true))
              var intent = Intent()
              intent.putExtra("selectList",userSelectList as Serializable)
              setResult(RESULT_OK,intent)
              finish()
          }


        }

        val registerForPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            if (it) {
                //打开相机
                var mediaStorageDir =  File(externalCacheDir?.path+"/TuXuanXuan");
                if (!mediaStorageDir.exists()) {
                    mediaStorageDir.mkdirs()
                }
                val mediaFile  = File(mediaStorageDir.path + File.separator + "${System.currentTimeMillis()}.png")
                mCurrentPhotoPath = mediaFile.absolutePath;
                //小于7.0版本
                var uriForFile :Uri= if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N){
                    Uri.fromFile(mediaFile )
                }else{
                    // 7.0 利用FileProvider
                    val authority: String = "$packageName.fileprovider" // 需要在配置文件中配置
                    FileProvider.getUriForFile(this, authority, mediaFile )
                }
                var intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                // 添加权限
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                intent.putExtra(MediaStore.EXTRA_OUTPUT,uriForFile)
                registerCamera.launch(intent)
            }else{
                Snackbar.make(binding.root,"请打开相机,否则无法拍照",Snackbar.LENGTH_LONG).show()
            }

        }


        // 多条目布局rv
        val gridLayoutManager = GridLayoutManager(this, 4)

        gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                if (position == 0) {
                    return 4
                } else {
                    return 1
                }
            }

        }
        binding.rvPhoto.layoutManager =gridLayoutManager

        binding.rvPhoto.adapter = SelectPhotoAdapter(this,topPhotoList,bottomPhotoList,object :SelectPhotoAdapter.SelectPhoneCallBack{
            override fun onOpenCamera() {
                //请求打开相机权限
                registerForPermission.launch(Manifest.permission.CAMERA)
            }

            override fun onScanBigImage(path: String) {
                var intent = Intent(this@SelectPhotoActivity,ScanImageActivity::class.java)
                intent.putExtra("path",path)
                startActivity(intent)
            }

            override fun onSelectPhotoTag(position: Int) {
                binding.rvPhoto.adapter?.notifyItemChanged(position)
            }

            override fun onGetList(selectList: List<MediaBean>) {
                userSelectList.clear()
                userSelectList.addAll(selectList)
                binding.tvNumber.text = "${selectList.size}"
            }

        })
    }

    /**
     * 查询手机所有照片
     */
    @SuppressLint("Range")
    private fun queryAllPhotoInfo() {
        totalPhotoList.clear()
        Thread {
            val mImageUri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            val projImage = arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE, MediaStore.Images.Media.DISPLAY_NAME)
            val mCursor = contentResolver.query(mImageUri, projImage, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", arrayOf("image/jpeg", "image/png"), MediaStore.Images.Media.DATE_MODIFIED + " desc")
            mCursor?.run {
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    val path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA))
                    val size = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media.SIZE)) / 1024
                    val displayName = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME))
                    //用于展示相册初始化界面
                    totalPhotoList.add(MediaBean(path, size, displayName, false))
                    // 获取该图片的父路径名-->多个文件夹
                    val dirPath = File(path).parentFile.absolutePath

                    //存储对应关系
                    if (allPhotosTemp.containsKey(dirPath)) {
                        val data: ArrayList<MediaBean> = allPhotosTemp[dirPath]!!
                        data.add(MediaBean(path, size, displayName, false))
                        continue
                    } else {
                        val data: ArrayList<MediaBean> = ArrayList()
                        data.add(MediaBean(path, size, displayName, false))
                        allPhotosTemp[dirPath] = data
                    }
                }
                mCursor.close()

            }
            //更新界面
            runOnUiThread {
                totalPhotoList?.let {
//                    pagingList(it, scanImageList)
                    disconnectList(totalPhotoList)
                    binding.rvPhoto.adapter?.notifyDataSetChanged()
                }
            }
        }.start()
    }

    /**
     * 拆分list 一个list 分为两个
     */
    fun disconnectList(list : List<MediaBean>){
        topPhotoList.clear()
        bottomPhotoList.clear()
        if (list.size >4){
            //subList 包头不包尾部
            topPhotoList.addAll(list.subList(0,4))
            bottomPhotoList.addAll(list.subList(4,list.size))

        }else{
            topPhotoList.addAll(list)
        }
    }




    /**
     * 对数据进行分页处理
     * pageSize 一页显示个数
     */
    private fun pagingList(it: ArrayList<MediaBean>, scanImageList: ArrayList<ScanImageBean>) {
        var scanImageList = arrayListOf<ScanImageBean>()
        var pageSize = 50;
        var totalPage: Int = it.size / pageSize + if (it.size % pageSize === 0) 0 else 1
        for (i in 1..totalPage) {
            var subList: List<MediaBean>
            if (i < totalPage) {
                subList = totalPhotoList.subList((i - 1) * pageSize, i * pageSize)
            } else {
                subList = totalPhotoList.subList((i - 1) * pageSize, totalPhotoList.size)
            }
            scanImageList.add(ScanImageBean(totalPage, i, subList))
        }
    }


}